package com.flute.framework.search;

import org.apache.lucene.index.FieldInvertState;
import org.apache.lucene.search.DefaultSimilarity;

import com.flute.framework.index.fieldbuilder.ScoreField;
import com.flute.framework.index.fieldbuilder.ScoreMap;
import com.flute.framework.search.ISearcher;

public class LayerSimilarity extends DefaultSimilarity {

	private static final long serialVersionUID = 9205110958050458000L;

	@Override
	public float computeNorm(String field, FieldInvertState state) {
		System.out.println(state);
		return 1;
	}

	/** Implemented as <code>1/sqrt(numTerms)</code>. */
	@Override
	public float lengthNorm(String fieldName, int numTerms) {
		return 1;
	}

	/** Implemented as <code>1/sqrt(sumOfSquaredWeights)</code>. */
	@Override
	public float queryNorm(float sumOfSquaredWeights) {
		return 1;
	}

	/** Implemented as <code>sqrt(freq)</code>. */
	@Override
	public float tf(float freq) {
		return 1;
	}

	/** Implemented as <code>1 / (distance + 1)</code>. */
	@Override
	public float sloppyFreq(int distance) {
		return 1.0f;
	}

	/** Implemented as <code>log(numDocs/(docFreq+1)) + 1</code>. */
	@Override
	public float idf(int docFreq, int numDocs) {
		return 1;
	}

	/** Implemented as <code>overlap / maxOverlap</code>. */
	@Override
	public float coord(int overlap, int maxOverlap) {
		return 1;
	}

	// Default false
	protected boolean disOverlaps;

	/**
	 * Determines whether overlap tokens (Tokens with 0 position increment) are
	 * ignored when computing norm. By default this is false, meaning overlap
	 * tokens are counted just like non-overlap tokens.
	 * <p>
	 * <b>WARNING</b>: This API is new and experimental, and may suddenly
	 * change.
	 * </p>
	 * 
	 * @see #computeNorm
	 */
	public void setDiscountOverlaps(boolean v) {
		disOverlaps = v;
	}

	/** @see #setDiscountOverlaps */
	public boolean getDiscountOverlaps() {
		return disOverlaps;
	}

	public float scorePayload(int docId, String fieldName, int start, int end,
			byte[] payload, int offset, int length) {
		try {
			ScoreMap map = ScoreMap.byteToScoreMap(payload);
			int name = 0;
			try {
				name = Integer.valueOf(fieldName);
			} catch (Exception e) {
			}
			if (fieldName == null || !map.contans(name)) {
				name = ScoreField.DEFAULT_SCORE;
			}

			float score = map.getScore(name);
			if (score >= ISearcher.SCORE_FACTOR) {
				score = ISearcher.SCORE_FACTOR - 1;
			}
			return score;
		} catch (Exception e) {
			return 0;
		}
	}
}
